package cn.wzvtc.rbac_mp.controller;

import cn.wzvtc.common.dto.Pagination;
import cn.wzvtc.common.dto.Result;
import cn.wzvtc.common.exception.MyException;
import cn.wzvtc.rbac_mp.dto.RoleBO;
import cn.wzvtc.rbac_mp.dto.RoleQuery;
import cn.wzvtc.rbac_mp.entity.Role;
import cn.wzvtc.rbac_mp.service.RoleService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author Shiwei Xu
 * @date 2020/6/11
 */
@RestController
@RequestMapping("role")
public class RoleController {

  @Autowired
  private RoleService roleService;

  /**
   * 多条件分页查询
   */
  @GetMapping("/query")
  public Result<IPage<Role>> list(RoleQuery roleQuery, Pagination pagination) {
    // 前端的查询参数 --> MybatisPlus的QueryWrapper对象
    String roleName = roleQuery.getRoleName();
    QueryWrapper<Role> wrapper = new QueryWrapper<>();
    wrapper.like(!StringUtils.isEmpty(roleName), "role_name", roleName);
    // 前端的分页参数 --> MybatisPlus的分页对象
    IPage<Role> page = pagination.toIPage();

    // 执行查询
    IPage<Role> result = roleService.page(page, wrapper);

    return Result.ok(result);
  }

  /**
   * 新增用户
   */
  @PostMapping
  public Result<Void> add(@RequestBody @Validated RoleBO roleBO) {
    // 更进一步的校验
    if (roleBO.getMenuIds().size() > 3) {
      throw new MyException("不能选择超过3个权限");
    }
    roleService.addRole(roleBO);
    return Result.ok();
  }

  /**
   * 更新用户
   */
  @PutMapping
  public Result<Void> update(@RequestBody RoleBO roleBO) {
    roleService.updateRole(roleBO);
    return Result.ok();
  }

  /**
   * 删除用户
   */
  @DeleteMapping
  public Result<Void> delete(@RequestBody List<Long> ids) {
    roleService.delete(ids);
    return Result.ok();
  }
}
